import React from 'react';
import PropTypes from 'prop-types';
import { Search, Loading, Balloon } from '@teamix/ui';
import Result from 'atComponents/ListEmpty/index';
import PathEllipsis from 'components/pathEllipsis';
import { YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import { ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import { navigateOpen } from 'utils/router';
import intl from '../../locale';

const { user_role } = window.FORCE.organization;

export default class SelectMenu extends React.Component {
  static propTypes = {
    selectValue: PropTypes.number,
    data: PropTypes.arrayOf(PropTypes.object),
    onChange: PropTypes.func,
    is_group_required: PropTypes.bool,
  };

  static defaultProps = {
    selectValue: 0,
    data: [],
    onChange: () => {},
    is_group_required: false,
    operateType: 'create',
  };

  constructor(props) {
    super(props);
    this.state = {
      search: '',
    };

    this.selectContainer = React.createRef();
    this.highlightTimer = null;
  }

  componentDidUpdate(prevProps) {
    if (this.props.highlightKey !== null && prevProps.highlightKey !== this.props.highlightKey) {
      clearTimeout(this.highlightTimer);
      this.highlightTimer = setTimeout(() => {
        try {
          const menuNode = this.selectContainer.current;
          const itemNode = menuNode.querySelector('.group-select-option.hover');
          itemNode && itemNode.scrollIntoViewIfNeeded();
        } catch (ex) {
          console.error(ex);
        }
      });
    }
  }

  componentWillUnmount() {
    clearTimeout(this.highlightTimer);
  }

  searchData = (search) => {
    this.setState(
      {
        search,
      },
      () => {
        this.props.getGroups(1, search);
      },
    );
  };

  renderOptions = () => {
    const { data, selectValue, isLoading, highlightKey, isTransfer } = this.props;
    if (isLoading) {
      return (
        <div className="group-select-loading">
          <Loading />
        </div>
      );
    }
    if (!data.length) {
      const desc = isTransfer ? '暂无可转移的代码组' : '暂无代码组';
      return (
        <div className="group-select-empty">
          <Result img="none" size="small" desc={desc} />
        </div>
      );
    }
    return (
      <div className="group-select-list">
        {data.map((item) => {
          return (
            <div
              className={`group-select-option ${highlightKey === item.value ? 'hover' : ''}`}
              onClick={() => {
                if (item.disabled) {
                  return;
                }
                this.props.onChange(item);
              }}
              key={item.id}
            >
              <div className="group-select-option-right">
                {Number(selectValue) === Number(item.value) ? (
                  <YunxiaoIcon type="true-line" className="select-icon" />
                ) : null}
              </div>
              <div className="group-select-option-left">
                {/*
                  1、isLastItemMoreImportant 设置名称超长时，出现省略号，否则超出部分被遮挡(前提是有宽度限制)；
                  2、style 覆盖一些样式，这里覆盖设置isLastItemMoreImportant时，弹层内容的颜色；
                */}
                <PathEllipsis isLastItemMoreImportant={false} path={item.label} />
                {/* <Balloon.Tooltip
                   trigger={
                     <div className="select-label one-line-ellipsis">{item.label}</div>
                   }
                   align="t"
                  >
                   {item.label}
                  </Balloon.Tooltip> */}
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  renderEmpty = () => {
    // 组必选且没有可选项时， 若是企业管理员，还需要保留搜索；若不是企业管理员，去掉搜索框，占位符显示：没有可选的代码组
    const { search } = this.state;
    const { is_group_required, data } = this.props;
    if (
      !search &&
      is_group_required &&
      !data.length &&
      !access(ORGANIZATION_ADMIN_ROLES, user_role)
    ) {
      return (
        <div className="no-group-message">
          {intl.get({
            id: 'code-assets.components.groupSelect.overlay.NoCodeGroupIsAvailable',
            defaultMessage: '没有可选的代码组',
          })}
        </div>
      );
    } else {
      return (
        <>
          <div className="group-select-search">
            <Search
              autoFocus
              shape="simple"
              placeholder={intl.get({
                id: 'code-assets.components.groupSelect.overlay.SearchForCodeGroups',
                defaultMessage: '搜索代码组',
              })}
              onKeyDown={this.props.handleKeyDown}
              value={search}
              onChange={this.searchData}
              style={{ width: '100%' }}
            />
          </div>
        </>
      );
    }
  };

  goCreateGroup = () => {
    // devops  需要跳转到我参与的组打开弹窗
    // coduep只需要打开弹窗
    if (!this.props.hasCreateGroupAccess) {
      return;
    }
    this.props.closePopFn();
    if (this.props.isDevops) {
      navigateOpen(`${window.location.origin}/groups?navKey=mine&showCreateGroupModal=true`);
    } else {
      this.props.goGroupModalFn();
    }
  };

  renderGoGroupLabel = () => {
    const { isDevops, hasCreateGroupAccess } = this.props;
    const ele = (
      <div className={`go-create-group-label ${hasCreateGroupAccess ? '' : 'disabled'}`}>
        <div
          onClick={this.goCreateGroup}
          style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}
        >
          <YunxiaoIcon type="add-line" style={{ marginRight: 8 }} size="small" />
          <span>
            {intl.get({
              id: 'code-assets.components.groupSelect.overlay.CreateACodeGroup',
              defaultMessage: '新建代码组',
            })}
          </span>
        </div>
        {hasCreateGroupAccess ? (
          <Balloon.Tooltip
            trigger={
              <ButtonIcon
                type="secondary"
                name="question-line"
                style={{ marginLeft: 4, display: 'inline-block' }}
              />
            }
            type="primary"
            align="t"
          >
            {isDevops
              ? intl.get({
                  id: 'code-assets.components.groupSelect.overlay.UseCodeGroupsToManage',
                  defaultMessage: '用代码组来管理多个代码库，前往 Codeup 新建代码组',
                })
              : intl.get({
                  id: 'code-assets.components.groupSelect.overlay.UseCodeGroupsToManage.1',
                  defaultMessage: '用代码组来管理多个代码库',
                })}
          </Balloon.Tooltip>
        ) : (
          <YunxiaoIcon type="question-line" style={{ marginLeft: 4, display: 'inline-block' }} />
        )}
      </div>
    );

    if (hasCreateGroupAccess) {
      return ele;
    } else {
      return (
        <Balloon.Tooltip trigger={ele} type="primary" align="t">
          {intl.get({
            id: 'code-assets.components.groupSelect.overlay.CurrentlyTheEnterpriseHasEnabled',
            defaultMessage: '当前企业开启了创建组的权限管控，如有需要请联系企业管理员修改',
          })}
        </Balloon.Tooltip>
      );
    }
  };

  render() {
    return (
      <div className="group-select-pop-container overlay-shadow">
        {this.renderEmpty()}
        {this.renderOptions()}
        {this.props.hasGoGroup && this.renderGoGroupLabel()}
      </div>
    );
  }
}
